// pages/editUser/editUser.js
Page({
  data: {
    user: null,
    genders: ['男', '女', '未知'],
    selectedGenderIndex: -1
  },

  onLoad: function(options) {
    this.loadUserInfo()
  },

  // 加载用户信息的方法
  loadUserInfo: function() {
    const userId = wx.getStorageSync('userId')
    if (!userId) {
      wx.showToast({
        title: '未登录',
        icon: 'none'
      })
      wx.navigateBack()
      return
    }

    wx.cloud.database().collection('users').doc(userId).get({
      success: res => {
        this.setData({
          user: res.data,
          selectedGenderIndex: this.data.genders.indexOf(res.data.gender)
        })
      },
      fail: err => {
        console.error('获取用户信息失败', err)
        wx.showToast({
          title: '获取信息失败',
          icon: 'none'
        })
      }
    })
  },

  // 处理性别选择变化
  onGenderChange: function(e) {
    this.setData({
      selectedGenderIndex: e.detail.value,
      ['user.gender']: this.data.genders[e.detail.value]
    })
  },

  // 处理表单提交
  submitForm: function(e) {
    const userId = wx.getStorageSync('userId')
    const { nickname, address } = e.detail.value
    const { gender } = this.data.user

    wx.cloud.database().collection('users').doc(userId).update({
      data: {
        nickname: nickname,
        gender: gender,
        address: address
      },
      success: res => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        wx.navigateBack()
      },
      fail: err => {
        console.error('保存用户信息失败', err)
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  }
})
